import React, {Component, cloneElement} from 'react';
import propTypes from 'prop-types';
import classNames from 'classnames';
import style from './Tabs.scss';

import TabNav from './TabNav';
import TabContent from './TabContent';

class Tabs extends Component {
  static propTypes = {}
  static defaultProps = {
    classPrefix: 'tabs',
    onChange: () => {}
  }
  constructor (props) {
    super(props);
    this.state = {};
    const curProps = this.props;
    let activeIndex;
    // 初始化 activeIndex state
    if ('activeIndex' in curProps) {
      activeIndex = curProps.activeIndex;
    } else if ('defaultActiveIndex' in curProps) {
      activeIndex = curProps.defaultActiveIndex;
    }
    this.state = {
      activeIndex,
      prevIndex: activeIndex
    };
  }

  componentWillReceiveProps (nextProps) {
    // 如果 props 传入 activeIndex，则直接更新
    if ('activeIndex' in nextProps) {
      this.setState({
        activeIndex: nextProps.activeIndex
      });
    }
  }

  handleTabClick (activeIndex) {
    const prevIndex = this.state.activeIndex;
    // 如果当前 activeIndex 与传入的 activeIndex 不一致，并且 props 中存在 defaultActiveIndex 时，则更新
    if (prevIndex !== activeIndex && 'defaultActiveIndex' in this.props) {
      this.setState({
        activeIndex,
        prevIndex
      })
    }
    // 更新后执行回调函数，抛出当前索引和上一次索引
    this.props.onChange({activeIndex, prevIndex});
  }

  renderTabNav () {
    const {classPrefix, children} = this.props;
    return (
      <TabNav
        key="tabBar"
        classPrefix={classPrefix}
        onTabClick={this.handleTabClick.bind(this)}
        panels={children}
        activeIndex={this.state.activeIndex}
      ></TabNav>
    )
  }

  renderTabContent () {
    const {classPrefix, children} = this.props;
    return (
      <TabContent
        key="tabContent"
        classPrefix={classPrefix}
        panels={children}
        activeIndex={this.state.activeIndex}
      ></TabContent>
    )
  }

  render () {
    const {className} = this.props;
    // 合并class
    const classes = classNames(className, 'ui-tabs');
    return (
      <div className={classes}>
        {this.renderTabNav()}
        {this.renderTabContent()}
      </div>
    );
  }
}

export default Tabs;
